<?php
apf_require_class("Bll_BLL");
class Bll_Portal_HomeProjectView extends BLL {

    /**
     * 访问次数+1
     * @param int $uid		--用户标识
     * @param int $pid		--子项目ID
     * @return boolean
     */
    public function inc_view_count($uid, $pid){
        if (empty($uid) || empty($pid)){
            return false;
        }
        return $this->get_view_count_dao()->inc_view_count($uid, $pid);
    }

    /**
     * 获取己经根据访问次数降序的子项目列表
     */
    public function get_sort_projects($uid = 0){
        $projects = $this->get_projects();
        $sorts = $this->get_view_count_by_uid($uid);

        if (empty($uid) || empty($sorts)) {
            return $projects;
        }

        uasort($sorts, function($a, $b){
            if ($a['count'] == $b['count']) return 0;
            return ($a['count'] > $b['count']) ? -1 : 1;
        });

        $result = array();
        foreach ($sorts as $sort){
            if (isset($projects[$sort['pid']])){
                $result[$sort['pid']] = $projects[$sort['pid']];
                unset($projects[$sort['pid']]);
            }
        }
        foreach ($projects as $key => $val){
            $result[$key] = $val;
        }
        return $result;
    }

    /**
     * 获取子项目列表
     */
    public function get_projects(){
        return APF::get_instance()->get_config('projects');
    }

    private function get_view_count_by_uid($uid){
        if (empty($uid)){
            return array();
        }
        $where = array(
            "uid" => $uid
        );
        return $this->get_view_count_dao()->find($where, "count desc", 0);
    }

    /**
     * return Dao_Portal_HomeData
     */
    private function get_view_count_dao(){
        return $this->get_dao('Dao_Portal_HomeProjectView');
    }

}